#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_TranslucentBackground);//设置窗口透明化
    this->setWindowFlags(Qt::FramelessWindowHint);//隐藏最大最小化等按键
    this->setWindowIcon(QIcon(":/img/agri.png"));
    windowInit();
    chartInit();
    d->openDb();
    connect(timer1,SIGNAL(timeout()),this,SLOT(get_Mqtt()));
    //connect(timer2,SIGNAL(timeout()),this,SLOT(detail_Mqtt()));

    connect(ui->switchBt1,SIGNAL(statusChanged(bool)),this,SLOT(switch1Ct()));
    connect(ui->switchBt2,SIGNAL(statusChanged(bool)),this,SLOT(switch2Ct()));
    connect(ui->switchBt3,SIGNAL(statusChanged(bool)),this,SLOT(switch3Ct()));
    connect(ui->loginBt,SIGNAL(clicked()), this, SLOT(loginCt()));
    connect(ui->registerBt,SIGNAL(clicked()), this, SLOT(registerCt()));
    connect(ui->alterBt,SIGNAL(clicked()), this, SLOT(alterCt()));
    connect(ui->exitBt,SIGNAL(clicked()), this, SLOT(exitCt()));

    connect(ui->revertBt,SIGNAL(clicked()), this, SLOT(deleteCt()));
    connect(ui->submitBt,SIGNAL(clicked()), this, SLOT(nodifyCt()));


    connect(ui->ledSlider,SIGNAL(valueChanged(int)), this, SLOT(sliderMoved1()));
    connect(ui->ledSlider,SIGNAL(sliderReleased()), this, SLOT(sliderReleased1()));
    connect(ui->fanSlider,SIGNAL(valueChanged(int)), this, SLOT(sliderMoved2()));
    connect(ui->fanSlider,SIGNAL(sliderReleased()), this, SLOT(sliderReleased2()));
    connect(ui->pumpSlider,SIGNAL(valueChanged(int)), this, SLOT(sliderMoved3()));
    connect(ui->pumpSlider,SIGNAL(sliderReleased()), this, SLOT(sliderReleased3()));

    connect(ui->userBt,SIGNAL(clicked()), this, SLOT(userCt()));
    connect(ui->dataBt,SIGNAL(clicked()), this, SLOT(dataCt()));
    connect(ui->weatherBt,SIGNAL(clicked()), this, SLOT(weatherCt()));
    connect(ui->locateBt,SIGNAL(clicked()), this, SLOT(on_LocateBt_Clicked()));
    connect(ui->closeBt,SIGNAL(clicked()), this, SLOT(windowcolse()));
    connect(ui->maxBt,SIGNAL(clicked()), this, SLOT(windowmax()));
    connect(ui->miniBt,SIGNAL(clicked()), this, SLOT(windowmin()));

    connect(&requst_mqtt,&QNetworkAccessManager::finished, this, &MainWindow::json_Mqtt);
    connect(&requst_detail_mqtt,&QNetworkAccessManager::finished, this, &MainWindow::json_detail);
    connect(&requst_ip,&QNetworkAccessManager::finished, this, &MainWindow::json_Ip);
    connect(&requst_city,&QNetworkAccessManager::finished, this, &MainWindow::json_City);
    connect(&requst_weather,&QNetworkAccessManager::finished, this, &MainWindow::json_Weather);
    connect(&requst_weathers,&QNetworkAccessManager::finished, this, &MainWindow::json_Weathers);

    // int zz = d.queryDb(db_list);
    // for(int i = 0;i < zz;i++){
    //     int a = db_list[i].userId;
    //     QString e =db_list[i].pass;
    //     QString z = db_list[i].token;
    // }
}
QString MainWindow::TEXT_COLOR(QString color,QString str){
    return "<font color= "+ color +">" + str + "</font> <font></font>";
}
void MainWindow::windowInit()
{
    ui->dataBt->setEnabled(false);
    ui->weatherBt->setEnabled(false);
    lab_weather_type_pic[0] = ui->label;
    lab_weather_type_pic[1] = ui->label_4;
    lab_weather_type_pic[2] = ui->label_7;
    lab_weather_type_pic[3] = ui->label_10;
    lab_weather_type_pic[4] = ui->label_13;
    lab_weather_type_pic[5] = ui->label_16;
    lab_temp_range[0] = ui->label_2;
    lab_temp_range[1] = ui->label_5;
    lab_temp_range[2] = ui->label_8;
    lab_temp_range[3] = ui->label_11;
    lab_temp_range[4] = ui->label_14;
    lab_temp_range[5] = ui->label_17;
    lab_date[0] = ui->label_3;
    lab_date[1] =ui->label_6;
    lab_date[2] =ui->label_9;
    lab_date[3] =ui->label_12;
    lab_date[4] =ui->label_15;
    lab_date[5] =ui->label_18;
    ui->switchBt1->setTextOn("灯开启");
    ui->switchBt1->setTextOff("灯关闭");
    ui->switchBt2->setTextOn("风扇开启");
    ui->switchBt2->setTextOff("风扇关闭");
    ui->switchBt3->setTextOn("水泵开启");
    ui->switchBt3->setTextOff("水泵关闭");
    ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::chartInit(){
    axisX1 = new QValueAxis();axisY1 = new QValueAxis();axisX2 = new QValueAxis();axisY2 = new QValueAxis();axisX3 = new QValueAxis();axisY3 = new QValueAxis();
    axisX1->setTitleText("时间/ms"); axisY1->setTitleText("温度/℃");
    axisX2->setTitleText("时间/ms"); axisY2->setTitleText("湿度/%");
    axisX3->setTitleText("时间/ms"); axisY3->setTitleText("光照强度/Lux");
    axisX1->setRange(0,AXIS_MAX_X); axisY1->setRange(0,70);//设置轴的最值
    axisX1->setTickCount(21);axisX1->setLabelFormat("%.1f");axisX1->setLabelsAngle(45);axisY1->setTickCount(6);
    axisX2->setRange(0,AXIS_MAX_X); axisY2->setRange(40,100);
    axisX2->setTickCount(21);axisX2->setLabelFormat("%.1f");axisX2->setLabelsAngle(45);axisY2->setTickCount(6);
    axisX3->setRange(0,AXIS_MAX_X); axisY3->setRange(10,130);
    axisX3->setTickCount(21);axisX3->setLabelFormat("%.1f");axisX3->setLabelsAngle(45);axisY3->setTickCount(6);

    serie1->setName("温度");
    serie2->setName("空气湿度");
    serie3->setName("光照强度");
    serie4->setName("土壤湿度");

    chart1->addSeries(serie1);
    chart2->addSeries(serie2);
    chart2->addSeries(serie4);
    chart3->addSeries(serie3);
    chart1->setAxisX(axisX1,serie1); chart1->setAxisY(axisY1,serie1);// 将轴添加到图表上
    chart2->setAxisX(axisX2,serie2); chart2->setAxisY(axisY2,serie2);
    chart2->setAxisX(axisX2,serie4); chart2->setAxisY(axisY2,serie4);
    chart3->setAxisX(axisX3,serie3); chart3->setAxisY(axisY3,serie3);

    ui->chartView1->setChart(chart1); ui->chartView1->setRenderHint(QPainter::Antialiasing);
    ui->chartView2->setChart(chart2); ui->chartView2->setRenderHint(QPainter::Antialiasing);
    ui->chartView3->setChart(chart3); ui->chartView3->setRenderHint(QPainter::Antialiasing);
}
/*******************************************************Slider槽函数************************************************************/
void MainWindow::sliderMoved1(){ui->ledLab->setText(QString::number(ui->ledSlider->value()));}
void MainWindow::sliderMoved2(){ui->fanLab->setText(QString::number(ui->fanSlider->value()));}
void MainWindow::sliderMoved3(){ui->pumpLab->setText(QString::number(ui->pumpSlider->value()));}
void MainWindow::sliderReleased1(){post_Mqtt(1);}
void MainWindow::sliderReleased2(){post_Mqtt(2);}
void MainWindow::sliderReleased3(){post_Mqtt(3);}
/*******************************************************按钮槽函数************************************************************/
void MainWindow::switch1Ct(){
    if(sw1){//由开转关
        ncontrol &= 0xFFF0;
        sw1 = false;
    }else{//由关转开
        ncontrol |= 0x0001;
        sw1 = true;
    }
    post_Mqtt(0);
}
void MainWindow::switch2Ct(){
    if(sw2){//默认关闭，由开转关
        ncontrol &= 0xFF0F;
        sw2 = false;
    }else{//由关转开
        ncontrol |= 0x0010;
        sw2 = true;
    }
    post_Mqtt(0);
}
void MainWindow::switch3Ct(){
    if(sw3){//默认关闭，由开转关
        ncontrol &= 0xF0FF;
        sw3 = false;
    }else{//由关转开
        ncontrol |= 0x0100;
        sw3 = true;
    }
    post_Mqtt(0);
}
void MainWindow::loginCt(){
    u->username = ui->userEdit->text();
    QString password = ui->passEdit->text();
    if(!password.isEmpty()){
        d->queryDb(1,u);
        if(password == u->pass){
            ui->userEdit->clear();
            ui->passEdit->clear();
            ui->dataBt->setEnabled(true);
            ui->weatherBt->setEnabled(true);
            ui->welLab->setText("欢迎使用农业监测系统 " + u->username + d->mapTo(u->x));
            ui->stackedWidget->setCurrentIndex(2);
            if(u->x != 2){
                if(u->x == 0) d->iden = 0;
                d->sqlModeInit(this,ui->userTable);
                d->tableviewInit(ui->userTable);
            }
        }else QMessageBox::information(NULL, "用户登录", "密码错误");
    }
}
void MainWindow::registerCt(){
    QString username = ui->userEdit->text();
    QString password = ui->passEdit->text();
    if(password.length() > 5 && password.length() < 10 && username.length() > 0 &&username.length() < 10){
        d->insertDb(username,password);
    }else QMessageBox::information(NULL, "用户注册", "用户名或密码非法");
}
void MainWindow::alterCt(){
    QString uname = ui->newnameEdit->text();
    QString upass_new = ui->newpassEdit->text();
    QString upass_od  = ui->oldpassEdit->text();
    if(upass_od == u->pass){
        if(!uname.isEmpty())
            if(d->updateDb1(u->username,uname)){
                u->username = uname;
                ui->oldpassEdit->clear();ui->newnameEdit->clear();
                ui->welLab->setText("欢迎使用农业监测系统 " + u->username + d->mapTo(u->x));//更新显示
            }else QMessageBox::information(NULL, "信息修改", "用户名修改失败");
        if(!upass_new.isEmpty())
            if(d->updateDb2(u->username,upass_new)){
                u->pass = upass_od;
                ui->oldpassEdit->clear();ui->newpassEdit->clear();
            }else QMessageBox::information(NULL, "信息修改", "密码修改失败");
    }
}
void MainWindow::deleteCt(){
    d->revert();
    // QString id = ui->useridEd->text();
    // if(!id.isEmpty())
        // if(d.deleteSqlData()){
        //     QMessageBox::information(NULL, "信息删除", "信息删除成功");
        //     ui->useridEd->clear();
        // }
        // else QMessageBox::information(NULL, "信息删除", "信息删除失败");
}
void MainWindow::nodifyCt(){
     d->summit();
}
void MainWindow::exitCt(){
    u = new struct_user();
    timer1->stop();
    timer2->stop();
    ui->dataBt->setEnabled(false);
    ui->weatherBt->setEnabled(false);
    ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_LocateBt_Clicked(){
    get_Ip();
}
/*********************************************oneNet相关函数*********************************************************/
void MainWindow::detail_Mqtt(){
    if(!(u->product.isEmpty() && u->device.isEmpty() && u->token.isEmpty()) )
    {
        QNetworkRequest request(QUrl(QString("https://iot-api.heclouds.com/device/detail?product_id=%1&device_name=%2").arg(u->product,u->device)));
        request.setRawHeader("Authorization",u->token.toUtf8());
        requst_detail_mqtt.get(request);
    }
}
void MainWindow::json_detail(QNetworkReply *reply){
    QString all = reply->readAll();
    //qDebug() << all;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(all.toUtf8());
    if(!jsonDocument.isNull()){
        QJsonObject object = jsonDocument.object();
        if(object.contains("data")){
            QJsonValue data = object.value("data");
            QJsonObject data_ob = data.toObject();
            bool zz = data_ob.value("enable_status").toBool();
            if(zz){
                if(!status){
                    ui->connect_icon->setPixmap(QPixmap(QString(":/img/connect.png")));
                    ui->switchBt1->setEnabled(true);
                    ui->switchBt2->setEnabled(true);
                    ui->switchBt3->setEnabled(true);
                }
                status = true;
            }else{
                if(status){//之前是ture
                    ui->connect_icon->setPixmap(QPixmap(QString(":/img/disconnect.png")));
                    ui->switchBt1->setEnabled(false);
                    ui->switchBt2->setEnabled(false);
                    ui->switchBt3->setEnabled(false);
                }
                status = false;
            }
        }
    }
}
void MainWindow::post_Mqtt(int type){
    if(!(u->product.isEmpty() && u->device.isEmpty() && u->token.isEmpty()) )
    {
        QJsonObject paramsObject;
        switch(type){
            case 0:paramsObject["control"] = ncontrol;break;
            case 1:paramsObject["Led"] = ui->ledSlider->value();break;
            case 2:paramsObject["Fan"] = ui->fanSlider->value();break;
            case 3:paramsObject["Pump"] = ui->pumpSlider->value();break;
        }

        QJsonObject jsonObject;
        jsonObject["product_id"] = u->product;
        jsonObject["device_name"] = u->device;
        jsonObject["params"] = paramsObject;
        // 创建 JSON 文档
        QJsonDocument jsonDocument(jsonObject);
        // 将 JSON 文档转换为 QByteArray
        QByteArray jsonData = jsonDocument.toJson();
        QNetworkAccessManager *networkManager = new QNetworkAccessManager();

        // 创建请求
        QNetworkRequest request(QUrl("https://iot-api.heclouds.com/thingmodel/set-device-property"));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        request.setRawHeader("Authorization", u->token.toUtf8());
        networkManager->post(request, jsonData);
    }
    // // 处理响应
    // QObject::connect(reply, &QNetworkReply::finished, [reply]() {
    //     if (reply->error() == QNetworkReply::NoError) {
    //         QByteArray responseData = reply->readAll();
    //         qDebug() << "Response:" << responseData;
    //     } else {
    //         qDebug() << "Error:" << reply->errorString();
    //     }
    //     reply->deleteLater(); // 清理内存
    // });
}
void MainWindow::get_Mqtt(){
    if( !(u->product.isEmpty() && u->device.isEmpty() && u->token.isEmpty()) )
    {
        QNetworkRequest request(QUrl(QString("https://iot-api.heclouds.com/thingmodel/query-device-property?product_id=%1&device_name=%2").arg(u->product,u->device)));
        request.setRawHeader("Authorization",u->token.toUtf8());
        requst_mqtt.get(request);
    }
}
void MainWindow::json_Mqtt(QNetworkReply *reply){
    int i;
    QString all = reply->readAll();
    //qDebug() << all;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(all.toUtf8());
    if(!jsonDocument.isNull()){
        QJsonObject object = jsonDocument.object();
        if(object.contains("data")){
            QJsonValue data = object.value("data");
            QJsonObject data_data;

            if(time != data.toArray().at(3).toObject().value("time")){//如果时间戳变化则更新数值和状态
                time = data.toArray().at(3).toObject().value("time");
                for(i = 0;i < 4;i++){//处理control及速度值
                    data_data = data.toArray().at(i).toObject();
                    data_mqtt[i] = data_data.value("value").toString();
                }
                for(i = 0;i < 4;i++){//处理传感器值
                    data_data = data.toArray().at(i + 4).toObject();
                    value[i] = data_data.value("value").toString().toInt();
                }
                data_data = data.toArray().at(8).toObject();//处理thre
                data_mqtt[4] = data_data.value("value").toString();
                QRegularExpression regex("\\d+");
                int j = 0;
                // 在字符串中查找匹配项
                QRegularExpressionMatchIterator i = regex.globalMatch(data_mqtt[4]);
                while (i.hasNext()) {
                    QRegularExpressionMatch match = i.next();
                    thre[j] = match.captured(0).toInt(); // 获取匹配到的数字
                    j++;
                }
                if(!status){
                    ui->connect_icon->setPixmap(QPixmap(QString(":/img/connect.png")));
                    ui->switchBt1->setEnabled(true);
                    ui->switchBt2->setEnabled(true);
                    ui->switchBt3->setEnabled(true);
                    ui->switchBt1->setChecked(false);ui->switchBt2->setChecked(false);ui->switchBt3->setChecked(false);
                    timer1->stop();timer1->start(3200);
                }
                status = true;
                count ++;
                mqtt_data_Update();
            }else {
                if(status){
                    ui->connect_icon->setPixmap(QPixmap(QString(":/img/disconnect.png")));
                    ui->switchBt1->setEnabled(false);
                    ui->switchBt2->setEnabled(false);
                    ui->switchBt3->setEnabled(false);
                    timer1->stop();timer1->start(200);//改变定时器时间，快速查询到设备情况
                }
                status = false;
            }
        }
    }
    reply->deleteLater(); //销毁请求对象
}
void MainWindow::mqtt_data_Update(){
    QString text = "";
    if(value[3] < thre[1]) text.append(TEXT_COLOR("red","温度过低"));
    else if(value[3] > thre[0]) text.append(TEXT_COLOR("red","温度过高"));
    else text.append("温度正常");
    if(value[2] < thre[3]) text.append("<br>"+TEXT_COLOR("red","土壤湿度过低"));
    else if(value[2] > thre[2]) text.append("<br>" + TEXT_COLOR("red","土壤湿度过高"));
    else text.append("<br>土壤湿度正常");
    if(value[1] < thre[5]) text.append("<br>" +TEXT_COLOR("red","光照强度过低"));
    else if(value[1] > thre[4]) text.append("<br>"+TEXT_COLOR("red","光照强度过高"));
    else text.append("<br>光照强度正常");
    ui->TextLab->setText(text);
    if(pcontrol != data_mqtt[0].toInt()){
        pcontrol = data_mqtt[0].toInt();
        switch(data_mqtt[0].toInt()){
        case 0:
            ui->switchBt1->setChecked(false);ui->switchBt2->setChecked(false);ui->switchBt3->setChecked(false);
            break;
        case 1:
            ui->switchBt1->setChecked(true);ui->switchBt2->setChecked(false);ui->switchBt3->setChecked(false);
            break;
        case 16:
            ui->switchBt1->setChecked(false);ui->switchBt2->setChecked(true);ui->switchBt3->setChecked(false);
            break;
        case 17:
            ui->switchBt1->setChecked(true);ui->switchBt2->setChecked(true);ui->switchBt3->setChecked(false);
            break;
        case 256:
            ui->switchBt1->setChecked(false);ui->switchBt2->setChecked(false);ui->switchBt3->setChecked(true);
            break;
        case 257:
            ui->switchBt1->setChecked(true);ui->switchBt2->setChecked(false);ui->switchBt3->setChecked(true);
            break;
        case 272:
            ui->switchBt1->setChecked(false);ui->switchBt2->setChecked(true);ui->switchBt3->setChecked(true);
            break;
        case 273:
            ui->switchBt1->setChecked(true);ui->switchBt2->setChecked(true);ui->switchBt3->setChecked(true);
            break;
        }
    }
    ui->tempLcd->display(value[3]);
    ui->humiLcd->display(value[0]);
    ui->intenLcd->display(value[1]);
    ui->ohumiLcd->display(value[2]);
    if(count > AXIS_MAX_X)//清空视图
    {
        serie1->remove(0);
        serie2->remove(0);
        serie3->remove(0);
        chart1->axisX()->setRange(count - AXIS_MAX_X,count);                // 更新X轴范围
        chart2->axisX()->setRange(count - AXIS_MAX_X,count);
        chart3->axisX()->setRange(count - AXIS_MAX_X,count);
    }
    //count ++;
    serie1->append(count,value[3]);
    serie2->append(count,value[0]);
    serie3->append(count,value[2]);
    serie4->append(count,value[1]);
}
/********************************************************api相关函数*********************************************************/
void MainWindow::get_Ip(void)
{
    QNetworkRequest request;
    request.setUrl(QUrl("http://whois.pconline.com.cn/ipJson.jsp?json=true"));
    requst_ip.get(request);
}
void MainWindow::json_Ip(QNetworkReply *reply)
{
    QString all = reply->readAll();
    QJsonDocument jsonDocument = QJsonDocument::fromJson(all.toUtf8());
    QJsonObject jsonObject = jsonDocument.object();
    QString ip = jsonObject.value("ip").toString();
    reply->deleteLater();
    get_City(ip);
}
void MainWindow::get_City(QString ip)
{
    QNetworkRequest request;
    request.setUrl(QUrl(QString("https://apis.map.qq.com/ws/location/v1/ip?ip=%1&key=6LDBZ-BF4HK-G2ZJA-ABCNH-3A44S-7OFZI").arg(ip)));
    requst_city.get(request);
}
void MainWindow::json_City(QNetworkReply *reply)
{
    QString all = reply->readAll();
    QJsonDocument jsonDocument = QJsonDocument::fromJson(all.toUtf8());
    if(!jsonDocument.isNull()){
        QJsonObject object = jsonDocument.object();
        if(object.contains("result")){
            QJsonValue result = object.value("result");
            if(result.isObject()){
                QJsonObject result_data = result.toObject();
                if(result_data.contains("ad_info"))
                {
                    QJsonValue ad_info = result_data.value("ad_info");
                    if(ad_info.isObject()){
                        QJsonObject ad_data = ad_info.toObject();
                        QString city = ad_data.value("city").toString();
                        ui->city->setText(city);
                    }
                }
                if(result_data.contains("location")){
                    QJsonValue location = result_data.value("location");
                    QJsonObject location_data = location.toObject();
                    QString lo;
                    lo = QString::number(location_data.value("lng").toDouble()) + "," + QString::number(location_data.value("lat").toDouble());
                    get_Weather(lo);
                    get_Weathers(lo);
                }
            }
        }
    }
    reply->deleteLater();
}
void MainWindow::get_Weather(QString city){//经度，纬度
    QNetworkRequest request;
    request.setUrl(QUrl(QString("https://devapi.qweather.com/v7/weather/now?location=%1&key=02bac1ba275a4f3a93b7ca50e0496aa5").arg(city)));
    requst_weather.get(request);  //get请求头
}
void MainWindow::json_Weather(QNetworkReply *reply)
{

    QString all = reply->readAll();
    //qDebug()<<"recv weather data!!"<<all;

    QJsonParseError err;
    QJsonDocument json_recv = QJsonDocument::fromJson(all.toUtf8(),&err);//解析json对象
    //qDebug() << err.error;
    if(!json_recv.isNull())
    {
        QJsonObject object = json_recv.object();

        if(object.contains("now"))
        {
            QJsonValue now = object.value("now");  // 获取指定 key 对应的 value
            if(now.isObject())
            {
                QJsonObject now_data = now.toObject();
                    ui->date->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd dddd"));
                    ui->temp->setText(now_data.value("temp").toString() + "℃");
                    ui->humidity->setText(now_data.value("humidity").toString() + "%");
                    ui->windDir->setText(now_data.value("windDir").toString());
                    ui->windScale->setText(now_data.value("windScale").toString() + "级风力");
                    ui->precip->setText(now_data.value("precip").toString() + "毫米降水");
                    ui->cloud->setText(now_data.value("cloud").toString() + "云量");
                    QString info = now_data.value("text").toString();
                    ui->weather_type->setText(info);
                    ui->weather_type->setMaximumSize(200,200);
                    ui->weather_type_icon->setScaledContents(true);
                    ui->weather_type_icon->setPixmap(QPixmap(QString(":/img/%1.png").arg(map1[info])));
            }
        }
    }
    else
    {
        qDebug()<<"请求数据失败";
    }
    reply->deleteLater(); //销毁请求对象
}
void MainWindow::get_Weathers(QString city){
    QNetworkRequest request;
    request.setUrl(QUrl(QString("https://devapi.qweather.com/v7/weather/7d?location=%1&key=02bac1ba275a4f3a93b7ca50e0496aa5").arg(city)));
    requst_weathers.get(request);  //get请求头
}
void MainWindow::json_Weathers(QNetworkReply *reply){
    QString all = reply->readAll();
    //qDebug()<<"recv weather data!!"<<all;

    QJsonParseError err;
    QJsonDocument json_recv = QJsonDocument::fromJson(all.toUtf8(),&err);//解析json对象
    qDebug() << err.error;
    if(!json_recv.isNull())
    {
        QJsonObject object = json_recv.object();

        if(object.contains("daily"))
        {
            QJsonValue daily = object.value("daily");  // 获取指定 key 对应的 value
            QJsonObject day;
            for(int i = 0;i < 6;i++){
                day = daily.toArray().at(i).toObject();
                date[i] = day.value("fxDate").toString();
                temperature[i] = day.value("tempMax").toString() + "-" + day.value("tempMin").toString();
                weather_type[i] = day.value("textDay").toString();
            }
        }
    }
    else
    {
        qDebug()<<"请求数据失败";
    }
    reply->deleteLater(); //销毁请求对象
    weather_data_Update();
}
void MainWindow::weather_data_Update(){
    ui->temp_range->setText(temperature[0] + "℃");
    for(int i = 0;i < 6;i++) {
        lab_temp_range[i]->setText(temperature[i] + "℃");
        lab_date[i]->setText(date[i]);
        lab_weather_type_pic[i]->setMaximumSize(70,70);
        lab_weather_type_pic[i]->setScaledContents(true);
        QStringList parts = weather_type[i].split("转");
        if (parts.size() > 0) {
            lab_weather_type_pic[i]->setPixmap(QPixmap(QString(":/img/%1.png").arg(map1[parts[0]])));
        } else {
            lab_weather_type_pic[i]->setPixmap(QPixmap(QString(":/img/%1.png").arg(map1[weather_type[i]])));
        }
    }
}

/********************************************************页面切换************************************************************/
void MainWindow::userCt(){
    if(u->username.isEmpty())ui->stackedWidget->setCurrentIndex(1);
    else ui->stackedWidget->setCurrentIndex(2);
}
void MainWindow::dataCt(){
    if(u->x == 2){//用户
        timer1->start(3200);
        //timer2->start(2000);
        ui->stackedWidget->setCurrentIndex(0);
    }else ui->stackedWidget->setCurrentIndex(3);
}
void MainWindow::weatherCt(){ui->stackedWidget->setCurrentIndex(4);}
/********************************************************鼠标事件重写*********************************************************/
void MainWindow::windowcolse()
{
    //QApplication::exit();
    this->close();
}
void MainWindow::windowmin()
{
    this->showMinimized();
}
void MainWindow::windowmax()
{

    this->showFullScreen();
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    diff_pos = event->globalPos() - this->pos();
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event){
    diff_pos = QPoint();
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if((event->buttons()==Qt::LeftButton) && (!this->isMaximized()) && (diff_pos!=QPoint())){
        QPoint pos = event->globalPos();
        this->move(pos - diff_pos);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}
